﻿using Inovout.Kuajing.Exports.Console.Web.Models;
using Inovout.Kuajing.Exports.Models;
using Inovout.Organizations.Models;
using Inovout.Organizations.Services;
using Inovout.People.Models;
using Inovout.People.Services;
using Inovout.Web.Mvc;
using System.Web.Mvc;
using System.Linq;
using Inovout.Organizations.Memberships.Models;
using Inovout.Kuajing.Exports.Services;
using Inovout.Services;
using Inovout.Locations;
using System.Collections.Generic;
using System;
using Inovout.Organizations.Memberships.Services;
using Inovout.NameCodeDictionary;

namespace Inovout.Kuajing.Exports.Console.Web.Controllers
{

    public class TraditionalOrderController : KJBaseController<TraditionalOrder>
    {

        private IPhoneService phoneService;
        private IEmployeeService employeeService;
        private ITraditionalOrderService traditionalOrderService;
        private IOrganizationUnitService organizationUnitService;
        private IConsigneeService consigneeService;
        private ILocationService locationService;
        private IExporterService exporterService;
        private ICommodityService commodityService;
        public TraditionalOrderController(IPhoneService phoneService, IEmployeeService employeeService,
            ITraditionalOrderService traditionalOrderService, IOrganizationUnitService organizationUnitService,
            IConsigneeService consigneeService, ILocationService locationService, IExporterService exporterService,
            ICommodityService commodityService)
        {
            this.phoneService = phoneService;
            this.employeeService = employeeService;
            this.traditionalOrderService = traditionalOrderService;
            this.organizationUnitService = organizationUnitService;
            this.consigneeService = consigneeService;
            this.locationService = locationService;
            this.exporterService = exporterService;
            this.commodityService = commodityService;
        }

        public ActionResult LocateExporter(string phone, string orderId)
        {
            if (!string.IsNullOrEmpty(phone))
            {
                Employee employee = null;
                ExporterInfo export = new ExporterInfo();

                //根据电话号码查询机构
                Phone orderPhone = phoneService.GetPhone(phone);
                if (orderPhone != null)
                {
                    employee = employeeService.FindByPhone(orderPhone);
                }
                if (employee != null)
                {
                    export.CommpanyName = employee.Organization.Name;
                    export.CommpanyCompareName = employee.Organization.Name;
                    export.CommpanyCode = employee.Organization.Id;
                    export.OrderPersonName = employee.Person.Name;
                    export.OrderPersonCode = employee.Id;
                    export.Phone = phone;
                    var telphones = employee.Person.Phones.AsQueryable().Where(model => model.Label.Equals(PhoneLabel.Tel));
                    if (telphones != null && telphones.Count() >0)
                    {
                        var telphone = telphones.First();
                        export.TelPhone = telphone.Value.ToString();
                    }
                }
                return View(export);
            }

            if (!string.IsNullOrEmpty(orderId))
            {
                TraditionalOrder traditionalOrder = traditionalOrderService.FindById(int.Parse(orderId));
                ExporterInfo exporter = new ExporterInfo();
                IRepositoryService<OrganizationMembership> membershipService = ComponentRegistry.Resolve<IRepositoryService<OrganizationMembership>>();
                OrganizationMembership organizationMembershiop = membershipService.FindById(traditionalOrder.Exporter.Membership.Id);
                exporter.orderId = traditionalOrder.Id;
                exporter.CommpanyCode = organizationMembershiop.Organization.Id;
                exporter.CommpanyName = organizationMembershiop.Organization.Name;
                exporter.OrderPersonName = traditionalOrder.OrderSignerName;
                exporter.OrderPersonCode = traditionalOrder.OrderSigner.Id;
                exporter.Phone = traditionalOrder.OrderSigner.Person.Phones.Where(c => c.Label == PhoneLabel.Mobile).First().Value;
                IEnumerable<Phone> telphone = traditionalOrder.OrderSigner.Person.Phones.Where(c => c.Label == PhoneLabel.Tel);
                if (telphone != null && telphone.Count() != 0)
                {
                    exporter.TelPhone = telphone.First().Value;
                }

                return View(exporter);
            }
            return View();
        }

        [HttpPost]
        public ActionResult LocateExporter(ExporterInfo exporterInfo)
        {
            OrganizationUnit organizationUnit = null;
            if (!exporterInfo.CommpanyCode.Equals(0))
            {
                organizationUnit = organizationUnitService.FindById(exporterInfo.CommpanyCode);
            }
            else
            {
                organizationUnit = new OrganizationUnit();
            }
            organizationUnit.Name = exporterInfo.CommpanyName.Trim();

            Location location = locationService.FindByName("中国");
            if (location == null)
            {
                location = new Location();
                location.ZoneCode = 2;
                location.ScopeCode = 1;
                location.Name = "中国";
                location.Parent = location;
                location.EnglishName = "china";
            }
            organizationUnit.Location = location;

            Employee employee;
            Phone phone;
            Person person;
            Phone tel;
            if (!exporterInfo.OrderPersonCode.Equals(0))
            {
                employee = employeeService.FindById(exporterInfo.OrderPersonCode);
                phone = employee.Person.Phones.AsQueryable<Phone>().Where<Phone>(model => model.Label == PhoneLabel.Mobile).First<Phone>();
                IEnumerable<Phone> telphones = employee.Person.Phones.AsQueryable<Phone>().Where<Phone>(model => model.Label == PhoneLabel.Tel);
                if (telphones != null && telphones.Count() != 0)
                {
                    tel = telphones.First();
                }
                else
                {
                    tel = new Phone() { Label = PhoneLabel.Tel };
                }
            }
            else
            {
                person = new Person();
                employee = new Employee();
                employee.Person = person;
                phone = new Phone() { Label = PhoneLabel.Mobile };
                tel = new Phone() { Label = PhoneLabel.Tel };
            }
            employee.Person.Name = exporterInfo.OrderPersonName.Trim();
            phone.Value = exporterInfo.Phone.Trim();
            if (!string.IsNullOrEmpty(exporterInfo.TelPhone))
            {
                tel.Value = exporterInfo.TelPhone.Trim();
                tel.Person = employee.Person;
                employee.Person.Phones.Add(tel);
            }
            phone.Person = employee.Person;
            employee.Person.Phones.Add(phone);

            //var exist_phone = employee.Person.Phones.Where(p => p.Value == phone.Value);
            //if (exist_phone == null)
            //{
            //    employee.Person.Phones.Add(phone);
            //}

            //var exist_tel = employee.Person.Phones.Where(p => p.Value == phone.Value);
            //if (exist_tel == null)
            //{
            //    employee.Person.Phones.Add(tel);
            //}   

            employee.Organization = organizationUnit;
            employeeService.Save(employee);

            Exporter exporter;
            IOrganizationMembershipService membershipService = ComponentRegistry.Resolve<OrganizationMembershipService>();
            OrganizationMembership organizationMembershiop = membershipService.FindByOrganizationUnit(organizationUnit);
            if (organizationMembershiop == null)
            {
                organizationMembershiop = new OrganizationMembership();
                organizationMembershiop.Organization = organizationUnit;
                exporter = new Exporter();
                exporter.Membership = organizationMembershiop;
            }
            else
            {
                exporter = exporterService.FindByMembership(organizationMembershiop);
            }


            TraditionalOrder traditionalOrder = new TraditionalOrder();
            if (exporterInfo.orderId != 0)
            {
                traditionalOrder = traditionalOrderService.FindById(exporterInfo.orderId);
            }

            traditionalOrder.Exporter = exporter;
            traditionalOrder.OrderSigner = employee;
            traditionalOrder.OrderSignerMobile = exporterInfo.Phone.Trim();
            traditionalOrder.OrderSignerName = exporterInfo.OrderPersonName.Trim();
            if (!string.IsNullOrEmpty(exporterInfo.TelPhone))
            {
                traditionalOrder.OrderSignerTel = exporterInfo.TelPhone.Trim();
            }


            traditionalOrderService.Save(traditionalOrder);
            return RedirectToAction("LocateConsignee", new { exporterName = exporterInfo.CommpanyName, orderPersonName = exporterInfo.OrderPersonName, orderId = traditionalOrder.Id });

        }

        [HttpGet]
        public ActionResult LocateConsignee(string exporterName, string orderPersonName, int orderId)
        {
            TraditionalOrder traditionalOrder = traditionalOrderService.FindById(orderId);
            ViewBag.OrderPersonName = orderPersonName;
            ConsigneeInfo conigneeInfo = new ConsigneeInfo();
            conigneeInfo.OrderId = orderId;

            IRepositoryService<OrganizationMembership> membershipService = ComponentRegistry.Resolve<IRepositoryService<OrganizationMembership>>();
            OrganizationMembership organizationMembershiop = membershipService.FindById(traditionalOrder.Exporter.Membership.Id);
            ViewBag.ExporterName = exporterName;
            if (traditionalOrder.Consignee != null)
            {
                conigneeInfo.CommpanyCode = traditionalOrder.Consignee.Organization.Id;
                conigneeInfo.CommpanyName = traditionalOrder.Consignee.Organization.Name;
                conigneeInfo.ConsigneeCode = traditionalOrder.Consignee.Id;
                conigneeInfo.ContactPersonCode = traditionalOrder.Contact.Id;
                conigneeInfo.ContactPersonName = traditionalOrder.ContactName;
                conigneeInfo.ContactPhone = traditionalOrder.Contact.Person.Phones.Where(p => p.Label == PhoneLabel.Mobile).First().Value;
                conigneeInfo.Country = traditionalOrder.ExportContryCode;
                conigneeInfo.Address = traditionalOrder.Consignee.Address;
            }

            IList<Location> listLocations = (IList<Location>)locationService.FindByParent(null);
            var countryList = listLocations.Select(c => new
              {
                  country = c.Id.ToString(),
                  countryName = c.Name
              });
            ViewData["countries"] = new SelectList(countryList.AsEnumerable(), "country", "countryName");
            return View(conigneeInfo);
        }

        [HttpPost]
        public ActionResult LocateConsignee(ConsigneeInfo conigneeInfo)
        {
            OrganizationUnit organizationUnit = null;
            if (!conigneeInfo.CommpanyCode.Equals(0))
            {
                organizationUnit = organizationUnitService.FindById(conigneeInfo.CommpanyCode);
            }
            else
            {
                organizationUnit = new OrganizationUnit();
            }
            organizationUnit.Name = conigneeInfo.CommpanyName;

            Location location = locationService.FindById(int.Parse(conigneeInfo.Country));
            organizationUnit.Location = location;


            Consignee consignee;
            if (!conigneeInfo.ConsigneeCode.Equals(0))
            {
                consignee = consigneeService.FindById(conigneeInfo.ConsigneeCode);
            }
            else
            {
                consignee = new Consignee();
            }
            consignee.Address = conigneeInfo.Address;
            consignee.Organization = organizationUnit;

            Employee employee;
            Person person;
            Phone phone = new Phone() { Label = PhoneLabel.Mobile };
            if (!conigneeInfo.ContactPersonCode.Equals(0))
            {
                employee = employeeService.FindById(conigneeInfo.ContactPersonCode);
                person = employee.Person;
                phone = employee.Person.Phones.Where(p => p.Value == conigneeInfo.ContactPhone).First();
            }
            else
            {
                person = new Person();
                employee = new Employee();
                employee.Person = person;

            }

            phone.Value = conigneeInfo.ContactPhone;
            person.Name = conigneeInfo.ContactPersonName;
            employee.Person.Phones.Add(phone);
            //var ph = employee.Person.Phones.Where(p => p.Value == phone.Value);
            //if (ph == null)
            //{
            //    employee.Person.Phones.Add(phone);
            //}
            employee.Organization = organizationUnit;
            employeeService.Save(employee);

            TraditionalOrder traditionalOrder = traditionalOrderService.FindById(conigneeInfo.OrderId);
            consignee.Exporters.Add(traditionalOrder.Exporter);

            traditionalOrder.Consignee = consignee;
            traditionalOrder.ConsigneeLocationCode = location.Code;
            traditionalOrder.ConsigneeLocationName = location.Name;
            traditionalOrder.Contact = employee;
            traditionalOrder.ContactMobile = conigneeInfo.ContactPhone;
            traditionalOrder.ContactName = conigneeInfo.ContactPersonName;
            traditionalOrderService.Save(traditionalOrder);

            return RedirectToAction("LocateCommodity", new { orderId = traditionalOrder.Id });
        }


        [HttpGet]
        public ActionResult LocateCommodity(int orderId)
        {
            TraditionalOrder traditionalOrder = traditionalOrderService.FindById(orderId);
            IRepositoryService<NameCode> nameCodeService = ComponentRegistry.Resolve<IRepositoryService<NameCode>>();
            var listnameCodes = NameCodeDictionaryManager.FindByCollectionName("币种");

            var countryList = listnameCodes.Select(c => new
            {
                TradeCurrency = c.Id.ToString(),
                CurrencyName = c.Name
            });
            ViewData["currencies"] = new SelectList(countryList.AsEnumerable(), "TradeCurrency", "CurrencyName");

            listnameCodes = NameCodeDictionaryManager.FindByCollectionName("价格条款");
            var listRules = listnameCodes.Select(c => new
            {
                PriceRule = c.Id.ToString(),
                PriceRuleName = c.Name
            });
            ViewData["rules"] = new SelectList(listRules.AsEnumerable(), "PriceRule", "PriceRuleName");

            return View(traditionalOrder);
        }

        [HttpPost]
        public ActionResult LocateCommodity(TraditionalOrder traditionalOrder, string commodities)
        {

            IRepositoryService<ExportCommodity> commodityService = ComponentRegistry.Resolve<IRepositoryService<ExportCommodity>>();
            IRepositoryService<Drawer> drawerService = ComponentRegistry.Resolve<IRepositoryService<Drawer>>();
            IRepositoryService<TraditionalOrderItem> traditionalOrderItemService = ComponentRegistry.Resolve<IRepositoryService<TraditionalOrderItem>>();
            List<CommodityInfo> commodityInfoList = (List<CommodityInfo>)Newtonsoft.Json.JsonConvert.DeserializeObject(commodities, typeof(List<CommodityInfo>));

            foreach (CommodityInfo commodityInfo in commodityInfoList)
            {
                Drawer drawer = new Drawer();
                if (commodityInfo.brawerCode == "0" && !string.IsNullOrEmpty(commodityInfo.Brand))
                {
                    drawer.Name = commodityInfo.Brawer;
                    //drawerService.Save(drawer);
                }
                else
                {
                    drawer = drawerService.FindById(int.Parse(commodityInfo.brawerCode));
                    //drawerService.Save(drawer);
                }


                ExportCommodity commodity = new ExportCommodity();
                if (commodityInfo.CommodityId == "0")
                {
                    Product product = new Product();
                    product.Brand = commodityInfo.Brand;
                    product.Name = commodityInfo.Name;
                    product.Model = commodityInfo.Model;
                    commodity.Product = product;
                    commodity.Exporter = traditionalOrder.Exporter;
                   // commodityService.Save(commodity);
                }
                else
                {
                    commodity = commodityService.FindById(int.Parse(commodityInfo.CommodityId));
                    commodity.Product.Brand= commodityInfo.Brand;
                    commodity.Product.Name= commodityInfo.Name;
                    commodity.Product.Model= commodityInfo.Model;
                    commodity.Exporter= traditionalOrder.Exporter;
                   // commodityService.Save(commodity);
                }


                TraditionalOrderItem traditionalOrderItem=null;
                if (commodityInfo.OrderItemId != "0") 
                {
                     traditionalOrderItem = traditionalOrderItemService.FindById(int.Parse(commodityInfo.OrderItemId));
                }
              
                if (traditionalOrderItem != null)
                {
                    traditionalOrderItem.CommodityName = commodityInfo.Name;
                    traditionalOrderItem.CommodityModel = commodityInfo.Model;
                    traditionalOrderItem.Commodity = commodity;
                    traditionalOrderItem.Price = decimal.Parse(commodityInfo.Price);
                    //traditionalOrderItem.Quantity =decimal.Parse(commodity.PackNum);
                    traditionalOrderItem.Sum = decimal.Parse(commodityInfo.Sum);
                    traditionalOrderItem.Order = traditionalOrder;
                    traditionalOrderItem.PackageQuantity = int.Parse(commodityInfo.PackNum);
                    traditionalOrderItem.MeasuringUnitName = commodityInfo.Unit;

                    traditionalOrderItem.Drawer = drawer;
                    traditionalOrderItem.DrawerTaxpayerNo = drawer.TaxpayerNo;
                    traditionalOrderItem.DrawerName = commodityInfo.Brand;//todo 重写
                    
                }
                else
                {
                    traditionalOrderItem = new TraditionalOrderItem();
                    traditionalOrderItem.CommodityName = commodityInfo.Name;
                    traditionalOrderItem.CommodityModel = commodityInfo.Model;
                    traditionalOrderItem.Commodity = commodity;
                    traditionalOrderItem.Price = decimal.Parse(commodityInfo.Price);
                    //traditionalOrderItem.Quantity =decimal.Parse(commodity.PackNum);
                    traditionalOrderItem.Sum = decimal.Parse(commodityInfo.Sum);
                    traditionalOrderItem.Order = traditionalOrder;
                    traditionalOrderItem.PackageQuantity = int.Parse(commodityInfo.PackNum);
                    traditionalOrderItem.MeasuringUnitName = commodityInfo.Unit;

                    traditionalOrderItem.Drawer = drawer;
                    traditionalOrderItem.DrawerTaxpayerNo = drawer.TaxpayerNo;
                    traditionalOrderItem.DrawerName = commodityInfo.Brand;//todo 重写
                }
                traditionalOrder.Items.Add(traditionalOrderItem);
            }
            traditionalOrderService.Save(traditionalOrder);
            return RedirectToAction("LocateLogistic", new { orderId = traditionalOrder.Id });
        }


        [HttpGet]
        public ActionResult LocateLogistic(int orderId)
        {
            IList<Location> listLocations = (IList<Location>)locationService.FindByParent(null);
            var countryList = listLocations.Select(c => new
            {
                ExportContryCode = c.Id.ToString(),
                ExportContryCodeName = c.Name
            });
            ViewData["countries"] = new SelectList(countryList.AsEnumerable(), "ExportContryCode", "ExportContryCodeName");

            //中国
            var locationId = 2;
            Location chinaLocation = locationService.FindById(locationId);
            IList<Location> listCities = (IList<Location>)locationService.FindByParent(chinaLocation);
            var cityList = listCities.Select(c => new
            {
                DeliveryCityCode = c.Id.ToString(),
                DeliveryCityName = c.Name
            });
            ViewData["cities"] = new SelectList(cityList.AsEnumerable(), "DeliveryCityCode", "DeliveryCityName");

            TraditionalOrder traditionalOrder = traditionalOrderService.FindById(orderId);
            return View(traditionalOrder);
        }

        [HttpPost]
        public ActionResult LocateLogistic(TraditionalOrder traditionalOrder)
        {
            traditionalOrderService.Save(traditionalOrder);
            return RedirectToAction("ListTraditionOrder");
        }

        [HttpGet]
        public ActionResult OrderSuccess(int orderId)
        {
            TraditionalOrder traditionalOrder = traditionalOrderService.FindById(orderId);
            return View(traditionalOrder);
        }

        [AllowAnonymous]
        [HttpPost]
        public JsonResult GetAllCommidity(int exporterId)
        {
            IRepositoryService<Exporter> exportService = ComponentRegistry.Resolve<IRepositoryService<Exporter>>();
            Exporter exporter = exportService.FindById(exporterId);
            IList<ExportCommodity> listCommodity = commodityService.FindCommodityByExporter(exporter);

            var data = from c in listCommodity
                       select new { Id = c.Id, PM = c.Product.Name, XH = c.Product.Model, PL = c.Product.Brand };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ListTraditionOrder()
        {
            return View(traditionalOrderService.FindAll());
        }
    }
}